<?php
namespace Home\Controller;
use Home\Controller\BaseController;
// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------
class QloginController extends BaseController{
    /**
     * 登录地址
     */
    public function login(){
        $type= I('get.type');
        empty($type) && $this->error('参数错误');
        $sns  = \Libs\ThinkOauth::getInstance($type); //加载ThinkOauth类并实例化一个对象
        redirect($sns->getRequestCodeURL()); //跳转到授权页面
    }
    /**
     * 登陆后回调地址
     */
    public function callback(){
        $code =  I('get.code');
        $type= I('get.type');
        $token = session('token');
        if(empty($token)){
            $sns  = \Libs\ThinkOauth::getInstance($type);
            //腾讯微博需传递的额外参数
            $extend = null;
            if($type == 'tencent'){
                $extend = array('openid' => I('get.openid'), 'openkey' =>  I('get.openkey'));
            }
            $token = $sns->getAccessToken($code , $extend); //获取第三方Token
            $user_sns_info = \Libs\ThinkOauthInfo::$type($token); //获取第三方传递回来的用户信息

            if($token['scope'] =='snsapi_login'){
                $user_sync_info = D('SyncLogin')->where(array('openid'=>$token['unionid']))->find(); //根据openid等参数查找同步登录表中的用户信息
            }else{
                $user_sync_info = D('SyncLogin')->getUserByOpenidAndType($token['openid'], $type); //根据openid等参数查找同步登录表中的用户信息
            }
            $user_sys_info = D('Users')->find($user_sync_info['uid']); //根据UID查找系统用户中是否有此用户
            if($user_sync_info['uid'] && $user_sys_info['user_id'] && $user_sync_info['uid'] == $user_sys_info['user_id']) { //曾经绑定过
                D('SyncLogin')->updateTokenByTokenAndType($token, $type);
                D('Users')->autoLogin($user_sys_info);
                redirect('http://'.$_SERVER['HTTP_HOST'].__ROOT__);
            }else{ //没绑定过，去注册页面
                session('token', $token);
                session('user_sns_info', $user_sns_info);
                $this->assign('user_sns_info', $user_sns_info);
                $this->assign('meta_title', "登陆" );
                $this->display('Public/reg');
            }
        }else{
                $this->assign('user_sns_info', session('user_sns_info'));
                $this->assign('meta_title', "登陆" );
                $this->display('Public/reg');
        }
    }

    /**
     * 第三方帐号集成 - 注册新账号
     */
    public function doregister(){
        //获取用户名、密码
        $username = I('mobile');
        $password = I('password');
        //上传头像，发现相同文件直接返回
        $avatar = I('avatar');
        //注册用户
        $user = M('Users');

        if ($password) {
            list($passwords, $salt) = password(trim($password));
        }
        
        if ($user->autoCheckToken($_POST)){
        
            $token = session('token');
            $user_sns_info = session('user_sns_info');
            if($user_sns_info['type'] == "WEIXIN"){
                $data['openid'] = $token['unionid'];
            }else{
                $data['openid'] = $token['openid'];
            }
            $tokens = M('SyncLogin')->where($data)->find();
            if($tokens){
                M('SyncLogin')->where($data)->delete();
            }
            
            $dates['user_mobile'] = I('mobile');
            $dates['user_mobile_bind'] = 1;
            $dates['user_name'] = I('username');
            $dates['user_passwd'] = $passwords;
            $dates['user_salt'] = $salt;
            $dates['user_avatar'] = $avatar;
            $dates['user_time'] = NOW_TIME;
            $dates['user_login_time'] = NOW_TIME;
            $dates['user_old_login_time'] = NOW_TIME;
            $dates['user_login_ip'] = get_client_ip(1);
            $dates['user_old_login_ip'] = get_client_ip(1);
            //判断是否已经存在此用户
            $where['user_mobile'] = I('mobile');
            $user = M('users')->where($where)->find();
            if($user){
                $id = $user['user_id'];
            }else{
                $id = $user->add($dates);
                if($id){
                    //新增SNS登录账号
                    D('SyncLogin')->update($id);
                    //登录用户
                    $uid = D('Users')->login($username, $password,1);
                    if($uid){
                        session('token',null);
                        session('user_sns_info',null);
                        $this->success('绑定成功', 'http://'.$_SERVER['HTTP_HOST'].__ROOT__);
                    }
                }else{
                    session('token',null);
                    session('user_sns_info',null);
                    $this->error('注册失败！');
                }
            }
            
            
        }
    }

    /**
     * 绑定本地帐号
     */
    public function dobind(){
        $username = I('mobile');
        $password = I('password');
        $uid = D('Users')->login($username, $password);
        if($uid > 0){
            //新增SNS登录账号
            $token = session('token');
            $user_sns_info = session('user_sns_info');
            if($user_sns_info['type'] == "WEIXIN"){
                $data['openid'] = $token['unionid'];
            }else{
                $data['openid'] = $token['openid'];
            }
            $tokens = M('SyncLogin')->where($data)->find();
            if($tokens){
                M('SyncLogin')->where($data)->delete();
            }
            
            if(D('SyncLogin')->update($uid)){
                session('token',null);
                session('user_sns_info',null);
                $this->success('第三方账号绑定成功', U('Home/Index/index'));
            }else{
                $this->error('新增SNS登录账号失败');
            }
        }
    }

    /**
     * 取消绑定本地帐号
     */
    public function cancelbind($uid){
        $condition['uid'] = $uid;
        $condition['type'] = $_GET['type'];
        $ret = D('SyncLogin')->where($condition)->delete();
        if($ret){
            $this->success('取消绑定成功');
        }else{
            $this->error('取消绑定失败');
        }
    }
    
    
    
}
